#!/user/bin/env set PYTHONIOENCODING=utf-8 && python -u
# -*- coding: utf-8 -*-

import json

from .primitives import Primitives

class JSONEncoder(json.JSONEncoder):

    def default(self, obj):
        if Primitives.is_datetime(obj):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif Primitives.is_decimal(obj):
            return float(obj)
        return json.JSONEncoder.default(self, obj)

class JSON:

    def to_json_string(obj):
        return json.dumps(obj, cls=JSONEncoder)

    def parse(str):
        try:
            return json.loads(str)
        except json.decoder.JSONDecodeError as error:
            raise Exception(repr(error))
